<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
        <el-form-item label="问卷的标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="请输入问卷的标题"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="发布状态" prop="publishStatus">
          <el-select v-model="queryParams.publishStatus" placeholder="请选择发布状态" clearable>
            <el-option
              v-for="dict in dict.type.publish_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['questionnaire:questionnaire:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['questionnaire:questionnaire:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['questionnaire:questionnaire:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['questionnaire:questionnaire:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="questionnaireList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="问卷id" align="center" prop="questionnaireId" />
        <el-table-column label="问卷的标题" align="center" prop="title" />
        <el-table-column label="图片" align="center" width="200">  
        <template slot-scope="scope">  
          <img :src="scope.row.picture" alt="图片" style="width: 100%; height: auto;">  
        </template>  
      </el-table-column> 
        <el-table-column label="问卷的描述" align="center" prop="description" />
        <el-table-column label="问卷创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发布状态" align="center" prop="publishStatus">
  <template slot-scope="scope">
    <div v-if="scope.row.status === 3"> 
      <dict-tag :options="dict.type.publish_status" :value="1" />
    </div>
    <div v-else>
      <dict-tag :options="dict.type.publish_status" :value="scope.row.publishStatus" />
    </div>
  </template>
</el-table-column>
  
        <el-table-column prop="status" label="审批状态" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.hdh_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
           
  
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
            <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateApprove(scope.row)"
            v-hasPermi="['questionnaire:questionnaire:editnoapprove']"
          >审批</el-button> -->
          
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateApprove(scope.row)"
           
          >查询</el-button>
           
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
  
    
  
  <el-dialog :title="questionnaireDetails.title" :visible.sync="viewDialogVisible" width="600px">
    <div class="questionnaire-title" style="text-align: center; font-weight: bold; font-size: 18px; margin-bottom: 20px;">
      {{ questionnaireDetails.title }}
    </div>
    <el-form :model="questionnaireDetails" label-width="120px" class="questionnaire-form">
    
      <div v-for="(question, index) in questionnaireDetails" :key="question.questionId" class="question-item">
        <el-form-item :label="'问题 ' + (index + 1)" class="question-form-item">
          <div class="question-text">{{ question.questionText }}</div>
  
          <!-- 根据问题类型显示不同的控件 -->
          <div v-if="question.questionType === '0'"> <!-- 单选 -->
            <el-radio-group v-model="question.selectedOption" class="option-group">
              <el-radio
                v-for="option in question.options"
                :key="option.optionId"
                :label="option.optionId"
              >{{ option.optionText }}</el-radio>
            </el-radio-group>
          </div>
  
          <div v-else-if="question.questionType === '1'"> <!-- 多选 -->
            <el-checkbox-group v-model="question.selectedOptions" class="option-group">
              <el-checkbox
                v-for="option in question.options"
                :key="option.optionId"
                :label="option.optionId"
              >{{ option.optionText }}</el-checkbox>
            </el-checkbox-group>
          </div>
  
          
          <div v-else-if="question.questionType === '2'"> 
            <el-input v-model="question.textAnswer" placeholder="请输入答案" />
          </div>
        </el-form-item>
      </div>
  
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false" size="small">关 闭</el-button>
      </div>
    </el-form>
  </el-dialog>
  
  <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问卷的标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入问卷的标题" />
        </el-form-item>
        <el-form-item label="问卷的描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="图片">  
      <img :src="form.picture" alt="学生图片" style="width: 100%; height: auto; max-width: 300px;" />  
      <!-- 假设您的 form 对象中有一个 picture 属性存储了图片的 URL -->  
    </el-form-item> 
       
       <el-form-item label="是否同意">
              <el-radio-group v-model="form.agree">
                <el-radio
                  v-for="dict in dict.type.sys_user_agree"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
        </el-form-item>

         <el-form-item label="批注" prop="comment">
          <el-input v-model="form.comment" type="textarea" placeholder="请输入批注内容" />
        </el-form-item>

<el-tabs>  
        
    <el-tab-pane label="审批结果">  
      <el-table :data="tableData" style="width: 100%">  
        <el-table-column prop="id" label="编号">  
          <template slot-scope="scope">  
            {{ generateUniqueId(scope.$index) }}  
          </template> 
        </el-table-column>  
        <el-table-column prop="userName" label="任务办理人">  
        </el-table-column>          
        <el-table-column prop="taskKeyId" label="任务的节点">  
        </el-table-column>  
         <el-table-column prop="taskName" label="任务的名称">  
        </el-table-column> 
        <el-table-column prop="message" label="批注">  
        </el-table-column>  
      </el-table>  
    </el-tab-pane>  

  </el-tabs> 
       
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  
  
  
  
      
    </div>
  </template>
  
  <script>
  import { getQuestionnaire ,getQuestionnaireDetails,getQuestionnaireComment,approveQuestionnaire,listFinished} from "@/api/questionnaire/questionnaire";
  import { getToken } from "@/utils/auth";
  
  export default {
  //  name: "Questionnaire",
    name: "QuestionnaireView",
    dicts: ['question_type', 'publish_status','hdh_status','sys_user_agree'],
    data() {
     
      return {
        viewDialogVisible: false,
        questionnaireDetails: [],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 子表选中数据
        checkedZxhQuestion: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 问卷信息表格数据
        questionnaireList: [],
        // 问题信息表格数据
        zxhQuestionList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
  
          // 图片导入参数
          uploadData: 
          {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/questionnaire/questionnaire/uploadMinio"
        },
  
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: null,
          description: null,
          publishStatus: null,
        },
        // 表单参数
        form: {},
  
        // 表单校验
        rules:
         {
          title: [
            { required: true, message: "问卷的标题不能为空", trigger: "blur" }
          ],
          description: [
            { required: true, message: "问卷的描述不能为空", trigger: "blur" }
          ],
          createTime: [
            { required: true, message: "问卷创建时间不能为空", trigger: "blur" }
          ],
        },
        
        url: '', 
        fit: 'contain',
        tableData:[]
       
           };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询问卷信息列表 */
      getList() {
        this.loading = true;
        listFinished(this.queryParams).then(response => {
          this.questionnaireList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          questionnaireId: null,
          title: null,
          description: null,
          createTime: null,
          publishStatus: null,
          updatedTime: null,
          createBy: null,
          version: null,
          picture: null
        };
        this.zxhQuestionList = [];
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.questionnaireId)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加问卷信息";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const questionnaireId = row.questionnaireId || this.ids
        getQuestionnaire(questionnaireId).then(response => {
          this.form = response.data;
          this.zxhQuestionList = response.data.zxhQuestionList;
          this.open = true;
          this.title = "修改问卷信息";
         
          this.url = this.form.picture;
          console.log('图片 URL:', this.url);
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.form.zxhQuestionList = this.zxhQuestionList;
            if (this.form.questionnaireId != null) {
                approveQuestionnaire(this.form).then(response => {
              this.$modal.msgSuccess("审批成功");
              this.open = false;
              this.getList();
            });

              updateQuestionnaire(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addQuestionnaire(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const questionnaireIds = row.questionnaireId || this.ids;
        this.$modal.confirm('是否确认删除问卷信息编号为"' + questionnaireIds + '"的数据项？').then(function() {
          return delQuestionnaire(questionnaireIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 问题信息序号 */
      rowZxhQuestionIndex({ row, rowIndex }) {
        row.index = rowIndex + 1;
      },
      /** 问题信息添加按钮操作 */
      handleAddZxhQuestion() {
        let obj = {};
        obj.questionText = "";
        obj.questionType = "";
        obj.createTime = "";
        this.zxhQuestionList.push(obj);
      },
      /** 问题信息删除按钮操作 */
      handleDeleteZxhQuestion() {
        if (this.checkedZxhQuestion.length == 0) {
          this.$modal.msgError("请先选择要删除的问题信息数据");
        } else {
          const zxhQuestionList = this.zxhQuestionList;
          const checkedZxhQuestion = this.checkedZxhQuestion;
          this.zxhQuestionList = zxhQuestionList.filter(function(item) {
            return checkedZxhQuestion.indexOf(item.index) == -1
          });
        }
      },
      /** 复选框选中数据 */
      handleZxhQuestionSelectionChange(selection) {
        this.checkedZxhQuestion = selection.map(item => item.index)
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('questionnaire/questionnaire/export', {
          ...this.queryParams
        }, `questionnaire_${new Date().getTime()}.xlsx`)
      },
  
  
  async handleView(row) {
    const questionnaireId = row.questionnaireId;
    try {
      const response = await getQuestionnaireDetails(questionnaireId);
      console.log('API Response:', response);
  
      if (Array.isArray(response)) {
        // 数据合并处理
        let questions = [];
        
        response.forEach(item => {
          // 查找该问题是否已存在
          let question = questions.find(q => q.questionId === item.questionId);
          if (!question) {
            // 如果该问题不存在，则新增
            question = {
              questionId: item.questionId,
              title: item.title,
              questionText: item.questionText,
              questionType: item.questionType,
              options: [],
              selectedOption: null, // 默认没有选项被选中
              selectedOptions: []   // 多选时保存选中的多个选项
            };
            questions.push(question);
          }
          
          // 将选项添加到问题的 options 数组中
          question.options.push({
            optionId: item.optionId,
            optionText: item.optionText
          });
        });
  
        this.questionnaireDetails = questions;
        this.viewDialogVisible = true;
      } else {
        this.$message.error("获取到的问卷详细信息格式不正确");
        console.log('Unexpected response structure:', response);
      }
    } catch (error) {
      console.error(error);
      this.$message.error("获取问卷详细信息失败: " + error.message);
    }
  },
  
      handlequestionnairesSubmit(questionnaireId){
          submitquestionnaire(questionnaireId).then(response => {
            console.log(response)
            this.getList();
            this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + "提交申请成功！" + "</div>", "提示框", { dangerouslyUseHTMLString: true });
         });
     },
     
      /** 审批按钮操作 */
      handleUpdateApprove(row) {
      this.reset();
    //   this.open = true;
    //   this.title = "审批学生信息";
      console.log(row);
      console.log(this.ids);
      const questionnaireId = row.questionnaireId || this.ids
      getQuestionnaireComment(questionnaireId).then(response => {
        console.log(response);
        this.form = response.data; 

        this.tableData=response.data.taskCommentVoList;
        this.open=true;
        this.title="审批学生信息"

      });

    },

    generateUniqueId(index) {  
      // 根据需要生成唯一的编号  
      return '' + (index + 1);  
    }
   
  
      
    }
  };
  </script>
  
  <style>
  .custom-dialog .el-dialog__body {
    background-color:beige /* 设置整个对话框背景为淡黄色 */
  }
  
  .questionnaire-form {
    padding: 10px;
    background-color: rgb(225, 242, 255); /* 设置表单背景色为淡黄色 */
  }
  
  .question-item {
    margin-bottom: 10px; /* 缩小每个问题项之间的行距 */
    background-color: rgb(225, 244, 255); /* 设置每个问题项的背景色 */
    padding: 10px;
    border-radius: 4px;
  }
  
  .question-item:last-child {
    margin-bottom: 2px; /* 缩小最后一个问题和下一个问题之间的间距 */
  }
  
  .question-text {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 6px; /* 缩小问题文本与选项之间的间距 */
  }
  
  .option-group {
    display: flex;
    flex-direction: column;
  }
  
  .option-group .el-radio,
  .option-group .el-checkbox {
    margin-bottom: 8px; /* 增加选项之间的间距 */
  }
  
  .text-area {
    width: 100%;
    margin-top: 6px; /* 调整文本框和选项之间的间距 */
  }
  
  .dialog-footer {
    text-align: right;
    padding: 10px 20px;
  }
  </style>